<?php
namespace Admin\Logic;

use Admin\Common\Category;
use Think\Log;
class StockLogic
{

    /**
     * 获取库存数据
     * @param int $id
     * @return bool|mixed
     */
    public static function getAll()
    {
        try{
            $stock = D('Stock as s');
            $data = $stock
                ->join('food_cate as c on s.cat_id = c.id')     //连接 分类 表
                ->field('s.*,c.cate_name')
                ->select();
            return $data;
        }catch (\Exception $e){
            return false;
        }

    }

    /**
     * 根据id 获取修改库存所需的数据
     * @param $id
     * @return bool|mixed
     */
    public static function getStockById($id)
    {
        // 根据id获取数据
        try {
            $stock = D('Stock as s');
            $data = $stock
                ->join('food_cate as c on s.cat_id = c.id')     //连接 分类 表
                ->where(['s.id'=>$id])
                ->field('s.*,c.cate_name')
                ->find();
            return $data;
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * 根据 商品名称 获取修改库存所需的数据
     * @param $name
     * @param $cate_id 分类ID
     * @return bool|mixed
     */
    public static function getStockByName($name = null, $cate_id = 0)
    {
        // 根据id获取数据
        try {
            $stock = D('Stock as s');
            $data = $stock
                ->join('food_cate as c on s.cat_id = c.id')     //连接 分类 表
                ->where(['s.cat_id' => $cate_id])
                ->where(['s.goods_name'=>['like','%'.$name.'%']])
                ->field('s.*,c.cate_name')
                ->select();
            return $data;
        } catch (\Exception $e) {
            return false;
        }
    }


    /**
     * 插入库存改动记录
     * @param $old_stock    $旧的库存
     * @param $new_stock    $新的库存
     * @param $arr      $更改的数据
     * @return bool|mixed
     */
    public static function isStockRecord($old_stock, $new_stock, $arr)
    {
        // 改动的值
        $stock_type = $old_stock>$new_stock?0:1;
        $stock = $stock_type==0?$old_stock-$new_stock:$new_stock-$old_stock;
        try{
            $stock_detail = D('StockDetail');
            $data = [
                'stock_id' => $arr['id'],
                'goods_name' => $arr['goods_name'],
                'unit' => $arr['unit'],
                'goods_price' => $arr['goods_price'],
                'stock' => $stock,
                'stock_type' => $stock_type,
                'remark' => $arr['remark'],
                'user_name' => $arr['user_name'],
                'created_at' => getDateTime(),
            ];
            $result = $stock_detail->add($data);
            return  $result;
        }catch (\Exception $e){
            return false;
        }


    }

    /**
     * 执行修改库存操作
     * @param $data
     * @return bool
     */
    public static function update($data)
    {
        try {
            $update = D('Stock')->save($data);
            return $update;
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * 执行添加库存操作
     * @param $data
     * @return bool
     */
    public static function create($data)
    {
        try {
            $data['user_id'] = I('session.user')['id'];
            $add = D('Stock')->add($data);
            //同时添加库存明细表
            if ($add) {
                $stock_detail = D('StockDetail');
                $data = [
                    'stock_id' => $add,
                    'goods_name' => $data['goods_name'],
                    'unit' => $data['unit'],
                    'goods_price' => $data['goods_price'],
                    'stock' => $data['stock'],
                    'stock_type' => 1,
                    'remark' => $data['remark'],
                    'user_name' => session('user.user_name'),
                    'created_at' => getDateTime(),
                ];
                $result = $stock_detail->add($data);
            }
            return $add;
        } catch (\Exception $e) {
            return false;
        }

    }

    /**
     * 删除单条数据
     * @param $id
     * @return mixed
     */
    public static function delete($id)
    {
        try {
            $data = D('Stock')->where(['id'=>$id])->delete();
            return $data;
        } catch (\Exception $e) {
            return false;
        }
    }

    public static function ajaxFood($ids)
    {
        try {
            $data = D('Stock')->where(['cat_id' => ['IN', $ids]])->order('id asc')->fetchSql(false)->select();
            return $data;
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * 库存明细查看
     * @param  [type] $stock_id [description]
     * @return [type]           [description]
     */
    public function detail($stock_id)
    {
        try {
            $stock_detail = D('StockDetail')->where(['stock_id' => $stock_id])->order('created_at desc')->select();
            return $stock_detail;
        } catch (\Exception $e) {
            return false;
        }
    }

    public static function findOne($id)
    {
        $data = D('Stock')->where(['id' => $id])
            ->field(['goods_name', 'unit', 'goods_price', 'stock'])
            ->find();
        return $data;
    }

    /**
     * 订单支付成功来更新库存明细表操作
     * @param  [type] $food [description]
     * @return [type]       [description]
     */
    public static function updateDetailOrder($food, $order_id)
    {
        $data = [];
        $msg = [];
        foreach ($food as $key => $value) {
            $detail = self::findOne($value['stock_id']);
            $data[] = [
                'stock_id' => $value['stock_id'],
                'goods_name' => $detail['goods_name'],
                'unit' => $detail['unit'],
                'goods_price' => $detail['goods_price'],
                'stock' => $value['deal_value'],
                'stock_type' => 0,
                'created_at' => getDateTime(),
                'remark' => $order_id,
                'user_name' => session('user.user_name')
            ];
            //减少库存
            M('stock')->where(['id' => $value['stock_id']])->setDec('stock', $value['deal_value']);

            if($detail['stock'] >= 0){
                if($detail['stock']-$value['deal_value'] <=0){
                    session('stock.'.$detail['goods_name'],$detail['stock']-$value['deal_value']);
                }
            } else {
                session('stock.'.$detail['goods_name'],$detail['stock']+$value['deal_value']);
            }





        }
        try {
            $stock_detail_id = M('stock_detail_log')->addAll($data);
            return $stock_detail_id;
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * 判断库存是还有，当==$num或<$num的时候为库存不足
     * @param $stock_id
     * @param int $num
     * @return array|bool
     */
    public static function isStockNotEnough($stock_id,$num = 0,$val)
    {
        try{
            $res = D('Stock')
                ->find($stock_id);
            if($res['stock'] < $num || $res['stock'] == $num){
                // 库存不足
                session('stock.'.$res['goods_name'],$res['stock']);
            }

        } catch (\Exception $e){
            return false;
        }
    }



}